import { ref, computed } from 'vue'
import pb from '../utils/pocketbase'
import type { RecordModel } from 'pocketbase'

// 全局认证状态
const currentUser = ref<RecordModel | null>(null)
const isLoading = ref(false)
const error = ref<string | null>(null)

// 计算属性
const isAuthenticated = computed(() => !!currentUser.value)

// 初始化认证状态
const initAuth = () => {
  currentUser.value = pb.authStore.model
}

// 注册用户
const register = async (userData: {
  email: string
  password: string
  passwordConfirm: string
  name: string
  emailVisibility?: boolean
}) => {
  isLoading.value = true
  error.value = null
  
  try {
    const record = await pb.collection('users').create(userData)
    console.log('用户注册成功:', record)
    return record
  } catch (err: any) {
    error.value = err.message || '注册失败'
    throw err
  } finally {
    isLoading.value = false
  }
}

// 用户登录
const login = async (email: string, password: string) => {
  isLoading.value = true
  error.value = null
  
  try {
    const authData = await pb.collection('users').authWithPassword(email, password)
    currentUser.value = authData.record
    console.log('用户登录成功:', authData)
    return authData
  } catch (err: any) {
    error.value = err.message || '登录失败'
    throw err
  } finally {
    isLoading.value = false
  }
}

// 用户登出
const logout = () => {
  pb.authStore.clear()
  currentUser.value = null
  error.value = null
}

// 获取所有用户列表
const getAllUsers = async () => {
  isLoading.value = true
  error.value = null
  
  try {
    const records = await pb.collection('users').getFullList({
      sort: '-created',
    })
    console.log('获取用户列表成功:', records)
    return records
  } catch (err: any) {
    error.value = err.message || '获取用户列表失败'
    throw err
  } finally {
    isLoading.value = false
  }
}

// 清除错误信息
const clearError = () => {
  error.value = null
}

export {
  currentUser,
  isLoading,
  error,
  isAuthenticated,
  initAuth,
  register,
  login,
  logout,
  getAllUsers,
  clearError
}
